package concurrent;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

/**
 * @author jack.wu
 * @since 2019/9/10
 */
public class ForkJoinTest {

    private static class SumTask extends RecursiveTask<Integer> {

        /**
         * 阙值
         */
        private int threshold = 2;

        private int[] src;
        private int fromIndex;
        private int toIndex;

        SumTask(int[] src, int fromIndex, int toIndex) {
            this.src = src;
            this.fromIndex = fromIndex;
            this.toIndex = toIndex;
        }

        @Override
        protected Integer compute() {

            if ((toIndex - fromIndex) < threshold) {
                int count = 0;
                System.out.println("from index:" + fromIndex + "\t to index:" + toIndex);
                for (int i = fromIndex; i <= toIndex; i++) {
                    count += src[i];
                }
                return count;
            } else {
                int mid = (fromIndex + toIndex) / 2;
                SumTask left = new SumTask(src, fromIndex, mid);
                SumTask right = new SumTask(src, mid + 1, toIndex);
                invokeAll(left, right);
                return left.join() + right.join();
            }
        }

        public static void main(String[] args) {
            int[] array = {4,9,0,1,83,22,92,11};
            ForkJoinPool pool = new ForkJoinPool();
            SumTask sumTask = new SumTask(array, 0, array.length - 1);
            long start = System.currentTimeMillis();
            pool.invoke(sumTask);
            System.out.println("The count is "+sumTask.join()+" spend time:"+(System.currentTimeMillis()-start)+"ms");
        }
    }

}
